package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/22
 * @description <a href="https://leetcode.cn/problems/remove-linked-list-elements/description/">...</a>
 */
public class Leetcode203_移除链表元素 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 借助哑头节点实现
     * 时间复杂度O(N) 需要遍历一遍链表
     * 空间复杂度O(1)
     */
    public ListNode removeElements(ListNode head, int val) {
        //边界条件校验
        if (head == null) {
            return head;
        }

        //借助哑头节点
        ListNode dummy = new ListNode();
        dummy.next = head;

        //遍历链表,删除指定节点
        ListNode cur = dummy;
        while (cur != null) {
            if (cur.next != null && cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }


        //返回头节点
        return dummy.next;
    }
}
